from flask import current_app,jsonify, make_response
from flask import g
from flask import request

from info import constants
from info.models import User, News, Category
from info.utils.common import login_data
from info.utils.response_code import RET
from . import index_blue
from flask import render_template


@index_blue.route('/news_list')
def news_list():
    # 1.传参
    # 要查询新闻数据，要获取的参数是cid编号（内容在哪个分类下面），页数，每页显示多少条
    # 可以不传，设置默认值
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    # 2.校验参数(因为有默认的参数，所以不需要校验数据有效性，但是可能会出现前端传的参数格式有问题)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.查询数据库（因为category_id的值取不到1，需要区分,status不为零则代表尚未审核通过）
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    # 获取查询后的数据(这是查询的模型对象的列表)
    news_list = paginate.items
    # 获取分页的总页面
    total_pages = paginate.pages
    # 获取当前的页码
    current_page = paginate.page

    news_dict_li = []  # 保存模型对象的to_basic_dict()字典的列表
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        'news_dict_li': news_dict_li,
        'total_page': total_pages,
        'current_page': current_page
    }

    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)


@index_blue.route('/')
@login_data
def index():
    user = g.user

    # 查询点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 显示数据分类
    # 查询数据库
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')

    # 传入模板
    category_dict_list = []
    for category in category_list:
        category_dict_list.append(category.to_dict())

    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li': news_dict_li,
        'category_dict_list': category_dict_list
    }

    # return make_response(jsonify(a=1,b=2))
    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def favicon_ico():
    # app.send_static_file是专门用来发送静态文件的，系统自带的路由映射中找static文件夹下的东西，也是用的这种方法
    return current_app.send_static_file('news/favicon.ico')
